package cn.wildfire.chat.kit.group;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.R;
import com.sourcemuch.im.caiba.R2;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.kit.GlideApp;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.conversation.ConversationActivity;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.GroupMember;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.GeneralCallback;

public class GroupInfoActivity extends WfcBaseActivity {

    /**
     * 刷新群组信息
     */
    private static final int REFRESH_GROUPINFO = 0x01;

    private String userId;
    private String groupId;
    private GroupInfo groupInfo;
    private boolean isJoined;
    private GroupViewModel groupViewModel;
    @BindView(R2.id.groupNameTextView)
    TextView groupNameTextView;
    @BindView(R2.id.groupNumberTextView)
    TextView groupNumberTextView;
    @BindView(R2.id.portraitImageView)
    ImageView groupPortraitImageView;

    @BindView(R2.id.actionButton)
    Button actionButton;

    private MaterialDialog dialog;
    private int actionCount = 0;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESH_GROUPINFO) {
                groupInfo = ChatManager.Instance().getGroupInfo(groupId, true);
                if (groupInfo == null) {
                    mHandler.sendEmptyMessageDelayed(REFRESH_GROUPINFO, 500);
                } else {
                    showGroupInfo(groupInfo);
                }
            }
        }
    };

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 3);
        setReplaceTitle(null, R.string.add_to_group);
        setSearchLayoutVisibility(false);
    }

    @Override
    protected void afterViews() {
        Intent intent = getIntent();
        groupId = intent.getStringExtra("groupId");
        groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);

        groupInfo = groupViewModel.getGroupInfo(groupId, true);
        if (groupInfo == null || groupInfo.name.contains(groupId)) {
            mHandler.sendEmptyMessage(REFRESH_GROUPINFO);
            groupViewModel.groupInfoUpdateLiveData().observe(this, groupInfos -> {
                for (GroupInfo info : groupInfos) {
                    if (info.target.equals(groupId)) {
                        this.groupInfo = info;
                        showGroupInfo(info);
                        dismissLoading();
                    }
                }
            });
        } else {
            groupInfo = groupViewModel.getGroupInfo(groupId, true);
            showGroupInfo(groupInfo);
        }
        List<GroupMember> groupMembers = groupViewModel.getGroupMembers(groupId, true);
        UserViewModel userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        userId = userViewModel.getUserId();
        if (groupMembers == null || groupMembers.isEmpty()) {
            showLoading();
            groupViewModel.groupMembersUpdateLiveData().observe(this, members -> {
                if (members.get(0).groupId.equals(groupId)) {
                    List<GroupMember> gMembers = groupViewModel.getGroupMembers(groupId, false);
                    for (GroupMember member : gMembers) {
                        if (member.type != GroupMember.GroupMemberType.Removed && member.memberId.equals(userId)) {
                            this.isJoined = true;
                        }
                    }
                    dismissLoading();
                    updateActionButtonStatus();
                }
            });
        } else {
            for (GroupMember member : groupMembers) {
                if (member.type != GroupMember.GroupMemberType.Removed && member.memberId.equals(userId)) {
                    this.isJoined = true;
                }
            }
            updateActionButtonStatus();
        }
        showGroupInfo(groupInfo);
    }

    private void updateActionButtonStatus() {
        if (isJoined) {
            actionButton.setText(getString(R.string.enter_group));
        } else {
            actionButton.setText(getString(R.string.add_group));
        }
    }

    private void showLoading() {
        actionCount++;
        if (dialog == null) {
            dialog = new MaterialDialog.Builder(this)
                    .progress(true, 100)
                    .build();
            dialog.show();
        }
    }

    private void dismissLoading() {
        if (dialog == null || !dialog.isShowing()) {
            return;
        }
        actionCount--;
        if (actionCount <= 0) {
            dialog.dismiss();
            dialog = null;
        }
    }

    private void showGroupInfo(GroupInfo groupInfo) {
        if (groupInfo == null) {
            return;
        }
        GlideApp.with(this)
                .load(groupInfo.portrait)
                .placeholder(R.mipmap.button_group)
                .into(groupPortraitImageView);
        groupNameTextView.setText("" + groupInfo.name);
        groupNumberTextView.setVisibility(View.VISIBLE);
        groupNumberTextView.setText(getString(R.string.group_total_number, "" + groupInfo.memberCount));
    }

    @Override
    protected int contentLayout() {
        return R.layout.group_info_activity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        showGroupInfo(groupInfo);
    }

    @OnClick(R2.id.actionButton)
    void action() {
        if (isJoined) {
            joined();
        } else {
            /**
             * modify by HEKE , 2019/8/28 21:16 TODO 增加群成员
             */
            ChatManager.Instance().addGroupMembers(groupInfo.target, Collections.singletonList(userId), Arrays.asList(0), null, new GeneralCallback() {
                @Override
                public void onSuccess() {
                   joined();
                }

                @Override
                public void onFail(int errorCode) {
                    if (errorCode == 248) {
                        ToastTip.tip(getString(R.string.nopermission_enter_group));
                    }
                }
            });
        }
    }

    private void joined() {
        try {
            Intent intent = ConversationActivity.buildConversationIntent(this, Conversation.ConversationType.Group, groupId, 0);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            GroupInfoActivity.this.finish();
        }
    }

}
